package ru.sgu.acm.dao;

import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import ru.sgu.acm.misc.Constants;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * XmlRpc imlementation of SubmitSourceDao.
 *
 * @author Vitaly Goldshteyn (VitalyGoldstein@gmail.com)
 */
public class SubmitSourceDaoXmlRpcImpl implements SubmitSourceDao {

    XmlRpcClientConfigImpl config;
    XmlRpcClient client;

    public SubmitSourceDaoXmlRpcImpl() {
        config = new XmlRpcClientConfigImpl();
        try {
            config.setServerURL(new URL(Constants.getXmlRpcUrl()));
        } catch (MalformedURLException e) {
            throw new IllegalStateException("Unable to get source from rpc server.", e);
        }
        client = new XmlRpcClient();
        client.setConfig(config);
    }

    public String getSource(long id) {
        String[] params = new String[]{Constants.getXmlRpcUser(),
                Constants.getXmlRpcPassword(), String.valueOf(id)};
        try {
            return (String)client.execute("getSource", params);
        } catch (XmlRpcException e) {
            throw new IllegalStateException("Unable to get source from rpc server.", e);
        }
    }

    public void putSource(long id, String source) {
        String[] params = new String[]{Constants.getXmlRpcUser(),
                Constants.getXmlRpcPassword(), String.valueOf(id), source};
        try {
            client.execute("putSource", params);
        } catch (XmlRpcException e) {
            throw new IllegalStateException("Unable to set source from rpc server.", e);
        }
    }
}
